package wh.coach.controller;

import java.util.Collections;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import wh.coach.web.controller.result.Result;
import wh.coach.domain.Project;
import wh.coach.domain.service.ProjectService;

/**
 * @Author xhw
 * @Date 2023/10/27
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/project")
@CrossOrigin
public class ProjectController {

    private final ProjectService projectService;

    public ProjectController(ProjectService projectService) {
        this.projectService = projectService;
    }

    @PostMapping
    public Result<Boolean> addProject(@RequestBody Project project) {
        try {
            projectService.create(project);
            log.info("新增项目成功，项目名称：{}", project.getSectionName());
            return Result.ok(true);
        } catch (Exception e) {
            log.error("新增项目失败，错误信息：{}", e.getMessage(), e);
            return Result.error("500", "添加失败:" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteProject(@PathVariable Long id) {
        try {
            boolean result = projectService.delete(id);
            return Result.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "删除失败:" + e.getMessage());
        }
    }

    @PutMapping("/")
    public Result<Boolean> updateProject(@RequestBody Project project) {
        try {
            projectService.update(project);
            return Result.ok(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "更新失败:" + e.getMessage());
        }
    }

    /**
     * 根据路径获取所有子树
     *
     * @param path
     * @return
     */
    @GetMapping("/projects/{path}")
    public Result<List<Project>> getChildren(@PathVariable String path) {
        try {
            List<Project> children = projectService.getChildren(path);
            return Result.ok(children);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ok(Collections.emptyList());
        }
    }

    @GetMapping("/all")
    public List<Project> tree() {
        return projectService.findAll();
    }

    @GetMapping("/{id}")
    public Project getById(@PathVariable("id") Long id) {
        return projectService.findById(id);
    }


}
